package com.markrfield.iRacingTelemetryView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class BackgroundService extends Service {
	
	private boolean runLoop = true;
	
	private final Handler handler = new Handler();
	

	@Override
	public IBinder onBind(Intent intent) {
		
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
	}
	
	@Override
	public void onStart(Intent intent, int startid) {
		handler.removeCallbacks(streamData);
		handler.post(streamData);
		
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		Log.w("iRacing", "OnDestroy");
		runLoop = false;
		
		
		handler.removeCallbacks(streamData);
				
	}
	
	private Runnable streamData = new Runnable() {
		
		ServerSocket ss = null;
		
		public void run() {
			try {
				// Create new ServerSocket, listening on specified port
				ss = new ServerSocket(8081);
							
				while(runLoop) {
					// Accept a new client
					Socket s = ss.accept();
					
					// Create a new buffered reader
					BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
					
					// Read line
					System.out.println(br.readLine());
					
					// Close BufferedReader and Socket.
					br.close();
					s.close();
					
				}
				
				ss.close();
				Log.w("iRacing", "Socket Closed");
				
				
			} catch (IOException e) {
				e.printStackTrace();
				Log.w("iRacing", "Error");
			}
		}
		
	};
	

}
